package com.lanren.familybookapp.ui.main.model;

import com.lanren.common.app.ApiUrl;
import com.lanren.common.base.impl.BaseModel;
import com.lanren.common.http.HttpManager;
import com.lanren.common.utils.GsonUtils;
import com.lanren.common.utils.LogUtils;
import com.lanren.easyhttp.callback.SimpleCallBack;
import com.lanren.easyhttp.exception.ApiException;
import com.lanren.easyhttp.model.ApiResult;
import com.lanren.familybookapp.app.AppUserHelper;
import com.lanren.familybookapp.ui.main.interfaces.IWelcomeModel;

import java.util.Map;

import io.reactivex.disposables.Disposable;

/**
 * @ClassName WelcomeModel
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2019/11/5 10:28
 * @Version 1.0
 */
public class WelcomeModel extends BaseModel {

    public WelcomeModel() {
        initDispoable();
    }

    public void checkLogin(final IWelcomeModel.WelcomeModelCheckLogin welcomeModelCheckLogin) {
        Disposable disposable = HttpManager.post(ApiUrl.API.USER_TOKEN_LOGIN)
                .headers(AppUserHelper.getHttpHeaders())
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        LogUtils.d("login code=" + e.getCode());
                        if (e.getCode() == 120) {
                            ApiResult apiResult = GsonUtils.fromJson(e.getData().toString(), ApiResult.class);
                            Map<String, Object> userBean = GsonUtils.fromJsonToMaps(apiResult.getData().toString());
                            LogUtils.d("login bean=" + GsonUtils.toJson(userBean));
                            AppUserHelper.getInstance().setKeyToken(userBean.get("token").toString());
                            welcomeModelCheckLogin.onSuccess();
                        } else if (e.getCode() == 200) {
                            welcomeModelCheckLogin.onSuccess();
                        } else {
                            welcomeModelCheckLogin.onError(e.getCode(), e.getMessage());
                        }
                    }

                    @Override
                    public void onSuccess(String s) {
                        welcomeModelCheckLogin.onSuccess();
                        LogUtils.d("login=" + GsonUtils.toJson(s));
                    }
                });

        addDisposable(disposable);
    }
}
